package com.dubbo.gmail.api.message;

import com.dubbo.gmail.api.service.AllService;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.springframework.context.ApplicationContext;

public class RequestDubboFactory<T extends AllService> {

    public static <T> T buildRequestDubbo(Class<T> allService, ApplicationContext context, URL url) {
//        URL url1 = url.setServiceInterface(allService.getName());
//        url1.toString();
        ReferenceBean<T> referenceBean = new ReferenceBean<>();
        referenceBean.setApplicationContext(context);
        referenceBean.setInterface(allService);
//        referenceBean.setUrl(buildUrlStr(url, allService.getName()));
        referenceBean.setUrl(url.setServiceInterface(allService.getName()).toString());
        T t = null;
        try {
            referenceBean.afterPropertiesSet();
            t = referenceBean.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * 构造格式 "dubbo://192.168.0.107:20881/com.dubbo.gmail.api.service.MatchResponseService"
     * @param url
     * @param serviceInterfaceName
     * @return
     */
    private static String buildUrlStr(URL url, String serviceInterfaceName) {
        StringBuilder stringBuilder = new StringBuilder();
        String urlString = stringBuilder.append(url.getProtocol()).append("://").append(url.getHost()).append(":")
                .append(url.getPort()).append("/").append(serviceInterfaceName).toString();
        return urlString;
    }
}
